package cli.command;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.FileTime;
import java.time.Instant;

public class Touch implements Command {
    private PrintWriter out;
    private Path currentPath;

    public Touch(PrintWriter out, Path currentPath) {
        this.out = out;
        this.currentPath = currentPath;
    }
    @Override
    public void handle(String[] args) {
        int pos = 0;
        if (pos >= args.length) {
            out.println("请指定一个文件路径！");
            return;
        }
        while (pos < args.length) {
            Path path;
            try {
                path = currentPath.resolve(args[pos]);
            } catch (InvalidPathException e) {
                out.println("无法识别文件路径" + args[pos] + "!");
                return;
            }
            pos++;
            if (Files.exists(path)) {
                try {
                    Files.setLastModifiedTime(path, FileTime.from(Instant.now()));
                } catch (IOException e) {
                    out.println("刷新文件"+currentPath.relativize(path)+"失败！");
                }
            } else {
                try {
                    Files.createFile(path);
                } catch (IOException e) {
                    out.println("创建文件"+currentPath.relativize(path)+"失败！");
                }
            }
        }
    }
}
